#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
保存选项对话框，用于设置保存图片的参数
"""

import os
import sys

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))

from PyQt5.QtWidgets import (
    QDialog, QVBoxLayout, QHBoxLayout, QGridLayout, QGroupBox,
    QLabel, QSpinBox, QPushButton, QCheckBox, QComboBox, QFileDialog
)
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QSettings

class SaveOptionsDialog(QDialog):
    """保存选项对话框"""

    def __init__(self, parent=None):
        """初始化对话框
        
        参数:
            parent: 父窗口对象
        """
        super().__init__(parent)
        
        # 设置窗口属性
        self.setWindowTitle("保存选项")
        self.setMinimumWidth(400)
        
        # 从配置文件读取上次的设置
        settings = QSettings("image_cutter", "config")
        self.format = settings.value("save_format", "PNG")
        self.quality = settings.value("save_quality", 95, int)
        self.path = settings.value("last_save_directory", "")
        self.include_coordinates = settings.value("include_coordinates", True, bool)
        self.remove_background = settings.value("remove_background", True, bool)
        
        # 设置布局
        self.setup_ui()
        
    def setup_ui(self):
        """设置UI界面"""
        layout = QVBoxLayout()
        
        # 文件格式选择
        format_group = QGroupBox("文件格式")
        format_layout = QHBoxLayout()
        
        format_layout.addWidget(QLabel("格式:"))
        self.format_combo = QComboBox()
        self.format_combo.addItems(["PNG", "JPG", "BMP", "TIFF"])
        self.format_combo.setCurrentText(self.format)
        self.format_combo.currentTextChanged.connect(self.on_format_changed)
        format_layout.addWidget(self.format_combo)
        
        # 质量设置（仅对JPG有效）
        self.quality_label = QLabel("质量:")
        format_layout.addWidget(self.quality_label)
        
        self.quality_spin = QSpinBox()
        self.quality_spin.setRange(1, 100)
        self.quality_spin.setValue(self.quality)
        self.quality_spin.setEnabled(self.format == "JPG")
        format_layout.addWidget(self.quality_spin)
        
        format_group.setLayout(format_layout)
        layout.addWidget(format_group)
        
        # 保存选项组
        options_group = QGroupBox("保存选项")
        options_layout = QVBoxLayout()
        
        # 是否包含坐标信息
        self.include_coords_checkbox = QCheckBox("在文件名中包含坐标信息")
        self.include_coords_checkbox.setChecked(self.include_coordinates)
        self.include_coords_checkbox.setToolTip("启用后，文件名会包含区域的坐标和大小信息")
        options_layout.addWidget(self.include_coords_checkbox)
        
        # 是否移除背景（仅PNG格式有效）
        self.remove_bg_checkbox = QCheckBox("移除背景（仅PNG格式）")
        self.remove_bg_checkbox.setChecked(self.remove_background)
        self.remove_bg_checkbox.setEnabled(self.format == "PNG")
        self.remove_bg_checkbox.setToolTip("启用后，PNG格式的图像会应用背景透明效果")
        options_layout.addWidget(self.remove_bg_checkbox)
        
        options_group.setLayout(options_layout)
        layout.addWidget(options_group)
        
        # 保存路径
        path_group = QGroupBox("保存位置")
        path_layout = QHBoxLayout()
        
        self.path_label = QLabel(self.path or "未选择")
        path_layout.addWidget(self.path_label)
        
        browse_btn = QPushButton("浏览...")
        browse_btn.clicked.connect(self.browse_path)
        path_layout.addWidget(browse_btn)
        
        path_group.setLayout(path_layout)
        layout.addWidget(path_group)
        
        # 按钮
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        
        ok_button = QPushButton("确定")
        ok_button.clicked.connect(self.accept)
        button_layout.addWidget(ok_button)
        
        cancel_button = QPushButton("取消")
        cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(cancel_button)
        
        layout.addLayout(button_layout)
        
        self.setLayout(layout)
        
    def on_format_changed(self, format):
        """格式改变事件
        
        参数:
            format (str): 新的格式
        """
        self.format = format
        # 只有JPG格式才启用质量设置
        self.quality_label.setEnabled(format == "JPG")
        self.quality_spin.setEnabled(format == "JPG")
        
        # 只有PNG格式才能设置背景透明
        if hasattr(self, 'remove_bg_checkbox'):
            self.remove_bg_checkbox.setEnabled(format == "PNG")
            if format != "PNG":
                self.remove_bg_checkbox.setChecked(False)
            else:
                self.remove_bg_checkbox.setChecked(True)
        
    def browse_path(self):
        """浏览保存路径"""
        directory = QFileDialog.getExistingDirectory(
            self, "选择保存目录", self.path or "")
        if directory:
            self.path = directory
            self.path_label.setText(directory)
            
    def get_settings(self):
        """获取设置
        
        返回:
            dict: 保存选项字典
        """
        # 保存设置到配置文件
        settings = QSettings("image_cutter", "config")
        settings.setValue("save_format", self.format_combo.currentText())
        settings.setValue("save_quality", self.quality_spin.value())
        settings.setValue("last_save_directory", self.path)
        settings.setValue("include_coordinates", self.include_coords_checkbox.isChecked())
        settings.setValue("remove_background", self.remove_bg_checkbox.isChecked())
        settings.sync()  # 确保设置被保存
        
        return {
            "format": self.format_combo.currentText(),
            "quality": self.quality_spin.value(),
            "path": self.path,
            "include_coordinates": self.include_coords_checkbox.isChecked(),
            "remove_background": self.remove_bg_checkbox.isChecked() and self.format_combo.currentText() == "PNG"
        } 